package de.bht.fb6.cg1.exercise2;

import java.awt.Color;

import de.bht.fb6.cg1.exercise1.CMY;

import ij.IJ;
import ij.ImagePlus;
import ij.gui.GenericDialog;
import ij.gui.NewImage;
import ij.plugin.PlugIn;
import ij.process.ImageProcessor;

/**
 * This class represents a plug in for ImageJ. It removes color components from an image.
 * 
 * @author Stephan Rehfeld <rehfeld (-at-) beuth-hochschule.de >
 * @author Dominik Eckelmann
 */
public class CMYComponentRemover implements PlugIn {

	/**
	 * The ImagePlus object of the loaded image.
	 */
	private final ImagePlus imp;
	
	/**
	 * This main method stars ImageJ and applies this plug in to the loaded image.
	 * 
	 * @param args Ignored.
	 */
	public static void main( final String args[] ) {
		IJ.open( "test.jpg" );
		final CMYComponentRemover rgbComponentRemover = new CMYComponentRemover( IJ.getImage() );
		rgbComponentRemover.run( "" );
	}

	/**
	 * This constructor creates a new CMYComponentRemover.
	 * 
	 * @param imp The ImagePlus object. Must not be null!
	 */
	public CMYComponentRemover( final ImagePlus imp ) {
		if( imp == null ) {
			throw new IllegalArgumentException( "The parameter 'imp' must not be null!" );
		}
		this.imp = imp;
	}
	
	@Override
	public void run( final String arg ) {
		imp.show();
		
		final GenericDialog gd = new GenericDialog( "Remove Components" );
		gd.addCheckbox( "Cyan", false );
		gd.addCheckbox( "Magenta", false );
		gd.addCheckbox( "Yellow", false );
		gd.showDialog();
		
		final boolean cyan    = gd.getNextBoolean();
		final boolean magenta = gd.getNextBoolean();
		final boolean yellow  = gd.getNextBoolean();
		
		final ImageProcessor ipOld = imp.getProcessor();
		final ImagePlus newImage = NewImage.createRGBImage( "Skaliertes Bild", ipOld.getWidth(), ipOld.getHeight(), 1, NewImage.FILL_BLACK );
		
		final ImageProcessor ipNew = newImage.getProcessor();
		
		final int[] pixOld = (int[])ipOld.getPixels();
		final int[] pixNew = (int[])ipNew.getPixels();
		
		for( int i = 0; i < pixNew.length; ++i ) {
			final int r = (pixOld[ i ] & 0x00ff0000) >> 16;
			final int g = (pixOld[ i ] & 0x0000ff00) >> 8;
			final int b = pixOld[ i ] & 0x000000ff;
			
			Color c = new Color(r, g, b);
			
			CMY cmy = new CMY(c);
			
			int[] cmycolor = cmy.getModelColor();
			if (cyan) cmycolor[0] = 0;
			if (magenta) cmycolor[1] = 0;
			if (yellow) cmycolor[2] = 0;
			
			cmy.setColor(cmycolor);
			Color newColor = cmy.getColor();
			
			pixNew[ i ] = (0xff << 24) | newColor.getRed() << 16 | newColor.getGreen() << 8 | newColor.getBlue();
		}
		
		newImage.show();
	}
	
}
